using System;
using System.Collections;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sedna.Core.Controller;
using Sedna.Core.Controller.Configurations;
using Sedna.Core.Controls.Support;
using Sedna.Core.DataBinding;
using Sedna.Core.Tiles.Contents;
using log4net;

namespace Sedna.Core.Controls
{
	/// <summary>
	/// Summary description for ActionCustomValidator.
	/// </summary>
	public class ActionCustomValidator : BaseValidator, IContent, IConfigurationAware
	{
        private ILog log = LogManager.GetLogger(typeof(ActionCustomValidator));
	    
        public const string VALIDATION_VALUE_PATH = "call['validationValue']";
        public const string ERROR_MESSAGE_PATH = "ec['validationErrorMessage']";
        public const string ERROR_MESSAGE_KEYS_PATH = "ec['validationErrorMessageKeys']";
	    
		private IConfiguration configuration;
		private string configurationId;

		private string textKey;
		private string errorMessageKey;

		private String contentPlaceHolderId;
        protected IDataBinder binder;

		public String ContentPlaceHolderId
		{
			get { return contentPlaceHolderId;}
			set { contentPlaceHolderId = value;}
		}

		public IConfiguration Configuration
		{
			get { return configuration; }
			set { configuration = value; }
		}

		[Bindable(true), Category("Sedna"), DefaultValue("configuration.default.ActionCustomValidator")]
		public string ConfigurationId
		{
			get { return configurationId; }
			set { configurationId = value; }
		}

		public string TextKey
		{
			get { return textKey; }
			set { textKey = value; }
		}

		public string ErrorMessageKey
		{
			get { return errorMessageKey; }
			set { errorMessageKey = value; }
		}

		public ActionCustomValidator(IConfiguration configuration)
		{
			Configuration = configuration;
            ConfigurationId = configuration.ObjectName;
		}

		protected void Build()
		{
			ID=Configuration.Id;		    
			
			TextKey = configuration.TextKey;
            ValidationGroup = configuration.ValidationGroup;

	
			IValidatorConfiguration validatorConfiguration = Configuration as IValidatorConfiguration;
			if (validatorConfiguration == null)
			{
				return;
			}

			ControlToValidate = validatorConfiguration.ControlToValidate;
			ErrorMessageKey = validatorConfiguration.ErrorMessageKey;
			Display = validatorConfiguration.Display;
            Enabled = configuration.IsEnabledForPrincipal() && configuration.Enabled;

		}

		protected override bool EvaluateIsValid()
		{
			IExecutionContext executionContext = ExecutionContext.GetCurrent(ClientID);

            if (!(configuration as IValidatorConfiguration).NoControl)
            {
                executionContext.SetPropertyValue(VALIDATION_VALUE_PATH, GetControlValidationValue(ControlToValidate));		    
            }
		    object isValidObj = ControlUtil.ExecuteOnValidate(executionContext, Context, Configuration, this.ClientID);

            if (isValidObj == null)
            {
                log.Warn("IsValid value not set after validation action execution.");
                return false;
            }

            if (!Convert.ToBoolean(isValidObj))
            {
                StringBuilder msg = new StringBuilder();

                msg.Append(configuration.GetLocalizedPostfixLabel(ErrorMessageKey, executionContext.GetPropertyValue(ERROR_MESSAGE_PATH) as string));

                IList msgKeys = executionContext.GetPropertyValue(ERROR_MESSAGE_KEYS_PATH) as IList;

                if (msgKeys != null)
                    foreach (string msgKey in msgKeys)
                    {
                        msg.Append(" ");
                        msg.Append(configuration.GetLocalizedPostfixLabel(msgKey, ""));
                    }

                ErrorMessage = msg.ToString().Trim();
                return false;
            }
            return true;
//            return Convert.ToBoolean(isValidObj);
		}

		protected override void OnInit(EventArgs e)
		{
			if (Configuration == null)
			{
				Configuration = (IConfiguration)SpringContextFactory.GetContext().GetObject(configurationId);
			}
            binder = new Sedna.Core.DataBinding.DataBinder(this, configuration, ExecutionContext.GetCurrent(ClientID));
            Build();
			base.OnInit (e);
		}

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Unbind();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            Bind();
            Text = configuration.GetLocalizedPostfixLabel(TextKey, Text);
            ErrorMessage = configuration.GetLocalizedPostfixLabel(ErrorMessageKey, ErrorMessage);

        }

	    protected virtual void Bind()
        {
            binder.Bind(new string[] { "Enabled", "ValidationGroup" });
            this.Enabled = this.Enabled && Configuration.IsEnabledForPrincipal();
        }

        protected virtual void Unbind()
        {
            binder.Unbind(new string[] { "Enabled", "ValidationGroup" });
        }

	    protected override bool ControlPropertiesValid()
	    {
            return ((configuration as IValidatorConfiguration).NoControl) ? true : base.ControlPropertiesValid();
	    }
	}
}
